package com.cursor.controller;

import com.cursor.entity.CursorAccount;
import com.cursor.entity.LicenseKeys;
import com.cursor.entity.Notification;
import com.cursor.service.CursorAccountService;
import com.cursor.service.LicenseKeysService;
import com.cursor.service.NotificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class ApiController {
    
    private final NotificationService notificationService;
    private final LicenseKeysService licenseKeysService;
    private final CursorAccountService cursorAccountService;
    
    @GetMapping("/notifications")
    public ResponseEntity<List<Notification>> getNotifications() {
        return ResponseEntity.ok(notificationService.getAllActiveNotifications());
    }
    
    @GetMapping("/license/{key}")
    public ResponseEntity<?> getLicenseInfo(@PathVariable String key) {
        Optional<LicenseKeys> licenseOpt = licenseKeysService.getLicenseByKey(key);
        
        if (!licenseOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        LicenseKeys license = licenseOpt.get();
        Map<String, String> response = new HashMap<>();
        
        // 检查许可证激活状态
        if (license.getActivationStatus() == null || license.getActivationStatus() == 0) {
            // 未激活状态，自动激活
            boolean activated = licenseKeysService.activateLicense(key);
            if (activated) {
                // 激活成功，重新获取最新许可证信息
                license = licenseKeysService.getLicenseByKey(key).get();
                response.put("message", "许可证已自动激活");
            } else {
                response.put("message", "许可证自动激活失败");
            }
        }
        
        // 获取许可证状态（已激活、未激活、已过期）
        String licenseStatus = licenseKeysService.getLicenseStatus(license);
        
        // 返回许可证信息
        response.put("key_status", licenseStatus); // 动态计算的状态
        response.put("account_type", license.getAccountType());
        
        // 添加积分使用信息
        response.put("cursorPoolUsageTotal", String.valueOf(license.getCursorPoolUsageTotal()));
        response.put("cursorPoolUsageUsed", String.valueOf(license.getCursorPoolUsageUsed()));
        
        if ("已激活".equals(licenseStatus)) {
            // 已激活，返回剩余天数
            response.put("days_left", licenseKeysService.getRemainingDays(license.getExpiryDate()));
            response.put("activation_status", "已激活");
            if (license.getActivationDate() != null) {
                response.put("activation_date", license.getActivationDate().toString());
            }
        } else if ("已过期".equals(licenseStatus)) {
            // 已过期
            response.put("days_left", "0天");
            response.put("activation_status", "已激活"); // 虽然已过期，但状态是激活的
            if (license.getActivationDate() != null) {
                response.put("activation_date", license.getActivationDate().toString());
            }
        } else {
            // 未激活
            response.put("days_left", "未激活");
            response.put("activation_status", "未激活");
            response.put("valid_days", license.getValidDays() != null ? license.getValidDays().toString() : "未设置");
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/account/{key}")
    public ResponseEntity<?> getCursorAccount(@PathVariable String key) {
        // 首先检查许可证是否存在
        Optional<LicenseKeys> licenseOpt = licenseKeysService.getLicenseByKey(key);
        if (!licenseOpt.isPresent()) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "许可证不存在");
            return ResponseEntity.status(404).body(errorResponse);
        }
        
        LicenseKeys license = licenseOpt.get();
        
        // 检查许可证状态
        String status = licenseKeysService.getLicenseStatus(license);
        if (!"已激活".equals(status)) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "许可证" + status);
            return ResponseEntity.status(403).body(errorResponse);
        }
        
        // 检查积分是否足够
        int remainingPoints = licenseKeysService.getRemainingPoints(license);
        if (remainingPoints < 50) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "积分不足");
            errorResponse.put("remaining_points", String.valueOf(remainingPoints));
            return ResponseEntity.status(403).body(errorResponse);
        }
        
        // 获取新账号 - 不检查是否已分配，允许多次获取
        Optional<CursorAccount> accountOpt = cursorAccountService.getAccountByKey(key);
        
        if (!accountOpt.isPresent()) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("error", "无法分配账号，请联系客服");
            errorResponse.put("message", "当前没有可用的账号，请联系客服");
            return ResponseEntity.status(500).body(errorResponse);
        }
        
        // 获取最新的许可证信息（积分已扣除）
        license = licenseKeysService.getLicenseByKey(key).get();
        
        CursorAccount account = accountOpt.get();
        Map<String, Object> response = new HashMap<>();
        response.put("email", account.getEmail());
        response.put("token", account.getToken());
        response.put("status", account.getStatus());
        response.put("points_used", license.getCursorPoolUsageUsed());
        response.put("cursorPoolUsageTotal", String.valueOf(license.getCursorPoolUsageTotal()));
        response.put("cursorPoolUsageUsed", String.valueOf(license.getCursorPoolUsageUsed()));
        response.put("points_remaining", licenseKeysService.getRemainingPoints(license));
        response.put("message", "成功获取新账号");
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/license/{key}/points")
    public ResponseEntity<?> getLicensePoints(@PathVariable String key) {
        Optional<LicenseKeys> licenseOpt = licenseKeysService.getLicenseByKey(key);
        
        if (!licenseOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        LicenseKeys license = licenseOpt.get();
        Map<String, Object> response = new HashMap<>();
        
        response.put("total_points", license.getCursorPoolUsageTotal());
        response.put("used_points", license.getCursorPoolUsageUsed());
        response.put("remaining_points", licenseKeysService.getRemainingPoints(license));
        response.put("status", licenseKeysService.getLicenseStatus(license));
        
        return ResponseEntity.ok(response);
    }
    

} 